package com.taiji.dianthus.controller.sys;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taiji.dianthus.common.BasicController;
import com.taiji.dianthus.common.BusinessMessage;
import com.taiji.dianthus.domain.sys.*;
import com.taiji.dianthus.service.sys.*;
import com.taiji.dianthus.util.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.taiji.dianthus.common.Constant.*;

/**
 * @ClassName SysRoleController
 * @Description 系统角色相关
 * @Author H.M
 * @Date 2019/12/24
 */
@RequestMapping(value = "/sys/role")
@Controller
public class SysRoleViewController extends BasicController {


    @Autowired
    private RoleService roleService;

    @Autowired
    private OrgService orgService;

    @Autowired
    private MenuRoleService menuRoleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private UserService userService;
    @Autowired
    private RoleUserService roleUserService;

    /**
     * 获取系统角色列表
     *
     * @param model
     * @param pageSize
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/list")
    public String listRole(HttpServletRequest request, Model model, Integer pageSize, Integer currentPage) {
        pageSize = getPageSize(pageSize);
        currentPage = getCurrentPage(currentPage);
        BusinessMessage message = roleService.listRoles(pageSize, currentPage);
        DSysUser currentUser = currentUser();
        //保存操作日志
        sysLogService.save(currentUser, LOG_OPERATION_QUERY, IPUtil.getIpAddr(request),
                "查询系统角色列表", message.getSuccess() ? 1 : 0, message.getMsg());
        model.addAttribute("data", message.getData());
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("menus", listMenu());
        return "/pages/sys/roleList";
    }


    /**
     * 跳转新增/编辑页面
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/add")
    public String addRole(Model model, String id) {
        DSysRole role = new DSysRole();
        if (!StringUtils.isEmpty(id)) {
            role = roleService.getRoleById(id);
        }
        model.addAttribute("role", role);
        model.addAttribute("currentUser", currentUser());
        model.addAttribute("menus", listMenu());
        return "/pages/sys/roleAdd";
    }


    /**
     * 跳转权限分配页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit")
    public String editRoleMenu(Model model, String roleId) {
        DSysRole role = roleService.getRoleById(roleId);
        //获取当前角色菜单
        List<DSysMenu> currentMenus = menuRoleService.getMenuByRoleId(roleId);
        //获取总菜单
        List<DSysMenu> allMenus = menuService.findAll();
        model.addAttribute("allMenus", allMenus);
        model.addAttribute("currentMenus", currentMenus);
        model.addAttribute("role", role);
        JSONArray jsonArray = new JSONArray();
        for (DSysMenu menu : allMenus) {
            JSONObject json = new JSONObject();
            json.put("id", menu.getId());
            if (StringUtils.isEmpty(menu.getParentId())) {
                json.put("pId", null);
                json.put("isParent", true);
            } else {
                json.put("pId", menu.getParentId());
            }
            json.put("name", menu.getMenuName());
            if (null != currentMenus && currentMenus.size() > 0 && currentMenus.contains(menu)) {
                json.put("checked", true);
            }
            json.put("open", true);
            jsonArray.add(json);
        }
        model.addAttribute("menuList", jsonArray.toJSONString());
        model.addAttribute("currentUser", currentUser());
        model.addAttribute("menus", listMenu());
        return "/pages/sys/roleDetail";
    }


    @RequestMapping(value = "/save")
    public String saveRole(HttpServletRequest request, Model model, DSysRole role) {
        BusinessMessage message = roleService.saveRole(role);
        //保存操作日志
        if (!StringUtils.isEmpty(role.getId())) {
            sysLogService.save(currentUser(), LOG_OPERATION_SAVE, IPUtil.getIpAddr(request),
                    "保存角色信息", message.getSuccess() ? 1 : 0, message.getMsg());
        } else {
            sysLogService.save(currentUser(), LOG_OPERATION_UPDATE, IPUtil.getIpAddr(request),
                    "更新角色[" + role.getRoleDesc() + "]信息", message.getSuccess() ? 1 : 0, message.getMsg());
        }
        return "redirect:/sys/role/list";
    }

    /**
     * 跳转权限分配页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/userEdit")
    public String userEdit(Model model, String id, HttpServletRequest request) {
        DSysRole role = roleService.getRoleById(id);

        //查询所有组织
        List<DSysOrg> orgList = orgService.listAll();
        JSONArray jsonArray = new JSONArray();
        for (DSysOrg org : orgList) {
            JSONObject json = new JSONObject();
            json.put("id", org.getId());
            json.put("pId", (null == org.getParentId() || "".equals(org.getParentId())) ? 0 : org.getParentId());
            json.put("name", org.getOrgName());
            //json.put("isParent", hasChild(org.getId()) == true ? true : false);
            json.put("open", org.getOrgLevel() <= 2 ? true : false);
            jsonArray.add(json);
        }
        List<DSysUser> roleUserList = userService.getUserByRoleId(id);
        //查询当前组织下用户
        List<DSysUser> userList = userService.listUserHasOrg();
        for (DSysUser user : userList) {
            JSONObject json = new JSONObject();
            json.put("id", user.getId());
            json.put("pId", user.getOrgId());
            json.put("name", user.getName());
            if (roleUserList != null && roleUserList.size() > 0 && roleUserList.contains(user)) {
                json.put("checked", true);
            }
            json.put("type", "user");
            jsonArray.add(json);
        }
        model.addAttribute("role", role);
        model.addAttribute("orgList", jsonArray.toJSONString());
        model.addAttribute("currentUser", currentUser());
        model.addAttribute("menus", listMenu());
        model.addAttribute("url", "/tjsms/sys/role/list?pageSize=10");
        return "pages/sys/roleUserAdd";
    }

    @RequestMapping(value = "/saveUserRole")
    @ResponseBody
    public JSONObject saveUserRole(HttpServletRequest request, String userIds, String roleId) {
        JSONObject message = new JSONObject();
        message.put("success", false);
        try {
            if ("".equals(userIds)) {
                message.put("msg", "选择的用户为空");
                return message;
            }
            String[] userIdsArr = userIds.split(",");
            if (userIdsArr.length == 0) {
                message.put("msg", "选择的用户为空");
                return message;
            }
            List<String> userIdList = Arrays.asList(userIdsArr);//新版用户集合
            List<String> preUserIds = roleUserService.getUserByRoleId(roleId);//旧版菜单集合
            //求差集
            List<String> differenceSet = userIdList.stream().filter(t -> !preUserIds.contains(t)).collect(Collectors.toList());
            List<String> differenceSet2 = preUserIds.stream().filter(t -> !userIdList.contains(t)).collect(Collectors.toList());
            //此处指的是将与l2重复的删除
            differenceSet.removeAll(differenceSet2);
            //此处指加上l2
            differenceSet.addAll(differenceSet2);
            for (int i = 0; i < differenceSet.size(); i++) {
                String did = differenceSet.get(i);
                //取差集中在旧ID中进行删除
                if (null != preUserIds && preUserIds.size() > 0 && !StringUtils.isEmpty(did) && preUserIds.contains(did)) {
                    roleUserService.delete(roleId, did);
                    //取差集中在新ID中进行存储
                } else if (!StringUtils.isEmpty(did) && userIdList.contains(did)) {
                    roleUserService.save(roleId, did);
                }
            }
            message.put("success", true);
            message.put("msg", "保存成功");

        } catch (Exception e) {
            e.printStackTrace();
            message.put("msg", "保存出错");

        }
        return message;
    }

    @RequestMapping(value = "/clearUserRole")
    @ResponseBody
    public JSONObject clearUserRole(HttpServletRequest request, String roleId) {
        JSONObject message = new JSONObject();
        message.put("success", false);
        try {
            roleUserService.deleteAllUserByRoleId(roleId);
            message.put("success", true);
            message.put("msg", "保存成功");

        } catch (Exception e) {
            e.printStackTrace();
            message.put("msg", "保存出错");

        }
        return message;
    }
}
